package com.youxin.admin.basic.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.youxin.admin.basic.entity.req.PushMsgReq;
import com.youxin.admin.basic.entity.search.PushMsgSearch;
import com.youxin.admin.basic.mapper.PushMsgMapper;
import com.youxin.admin.basic.model.PushMsg;
import com.youxin.admin.basic.service.PushMsgService;
import com.youxin.admin.basic.service.manager.ImManager;
import com.youxin.base.TPage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.stream.Collectors;

/**
 * description: PushMsgServiceImpl <br>
 * date: 2020/3/4 17:00 <br>
 * author: llkj <br>
 * version: 1.0 <br>
 */
@Service
public class PushMsgServiceImpl extends ServiceImpl<PushMsgMapper, PushMsg> implements PushMsgService {

    private Logger log = LoggerFactory.getLogger(this.getClass());
    @Resource
    private ImManager imManager;

    @Override
    public TPage<PushMsg> getList(PushMsgSearch pushMsgSearch) {
        LambdaQueryWrapper<PushMsg> queryWrapper = new LambdaQueryWrapper<>();
        if(!StringUtils.isEmpty(pushMsgSearch.getTitle())){
            queryWrapper.like(PushMsg::getTitle,pushMsgSearch.getTitle());
        }
        queryWrapper.orderByDesc(PushMsg::getCreateTime);
        IPage<PushMsg> page = this.baseMapper.selectPage(new Page<>(pushMsgSearch.getCurrentPage(),pushMsgSearch.getShowCount()),queryWrapper);
        return TPage.page(page.getRecords(),page.getTotal());
    }

    @Override
    public void setPushMsg(String userName, PushMsgReq pushMsgDto) {
        PushMsg pushMsg = new PushMsg();
        pushMsg.setMessage(pushMsgDto.getMessage());
        pushMsg.setTitle(pushMsgDto.getTitle());
        pushMsg.setCreateUser(userName);
        pushMsg.setUserNos(JSONObject.toJSONString(pushMsgDto.getUserNos()));
        String terminalType = pushMsgDto.getTerminalType().stream().map(item -> String.valueOf(item)).collect(Collectors.joining(","));
        pushMsg.setTerminalType(terminalType);
        pushMsg.setCreateTime(LocalDateTime.now());
        pushMsg.setToAll(pushMsgDto.getToAll());
        save(pushMsg);
        log.info("保存推送消息,data={}", JSONObject.toJSONString(pushMsg));

        imManager.pushCustomMsg(pushMsgDto.getTitle(),pushMsgDto.getMessage(), pushMsgDto.getTerminalType(), pushMsgDto.getUserNos(), pushMsgDto.getToAll());
    }
}
